package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.GZIPInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GZIPDecompressesGzippedFileIntoAnotherFile {
	public static final int BUFF_SIZE = 2048;


	public static void decompressFile(final File toDecompress,
	                                  final File destinationFile) throws IOException {


		InputStream istream = null;
		OutputStream ostream = null;
		try {

			ostream = new BufferedOutputStream(new FileOutputStream(
					destinationFile), BUFF_SIZE);
			istream = getCompressedFileAsStream(toDecompress);
			transferStream(istream, ostream);
		} finally {
			if (istream != null) {
				istream.close();
			}
			if (ostream != null) {
				ostream.close();
			}
		}
	}


	public static InputStream getCompressedFileAsStream(final File file)
			throws IOException {
		return new GZIPInputStream(new BufferedInputStream(
				new FileInputStream(file)));
	}


	protected static void transferStream(final InputStream istream,
	                                     final OutputStream ostream) throws IOException {
		final byte[] inBuf = new byte[BUFF_SIZE];
		int readBytes = istream.read(inBuf);
		while (readBytes >= 0) {
			ostream.write(inBuf, 0, readBytes);
			readBytes = istream.read(inBuf);
		}
	}
}
